<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/02/28
 */
namespace common\logic;

use yii;
use common\models\User as UserModel;

class User {
    public static function getUsers($uids) {
        $r = UserModel::findAll(['id' => $uids]);
        return $r;
    }

    public static function getNames($uids) {
        $users = self::getUsers($uids);
        $res = [];
        foreach ($users as $model) {
            $res[$model->id] = self::getNameByModel($model);
        }
        return $res;
    }
    public static function getNameByModel($model){
        return $model->nickname ?: ($model->username ?: substr_replace($model->getAttribute('phone'), '****', -8, 4));
    }

    public static function addFundAmount($uid, $amount) {
        Yii::$app->db->createCommand()->update('user', [
            'fund_amount' => new yii\db\Expression("fund_amount+$amount"),
        ], "id=$uid")->execute();
    }

    /**
     * 不check合法性，调用者保证事务
     * @param $uid
     * @param $amount
     */
    public static function useFundAmount($uid, $amount) {
        Yii::$app->db->createCommand()->update('user', [
            'fund_amount' => new yii\db\Expression("fund_amount-$amount"),
        ], "id=$uid")->execute();
    }

    public static function getFundAmount($uid) {
        $newFund = Yii::$app->db->createCommand("select fund_amount from `user` where id=$uid")->queryScalar();
        return $newFund;
    }
}
